//
//  SignalCountingViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 10/19/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "SignalCountingViewController.h"

@interface SignalCountingViewController ()

@end

@implementation SignalCountingViewController

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 260;//216
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;


static const int TIMING_RING1_GRAPH_INITIAL_POSITION_X=10;
static const int TIMING_RING1_GRAPH_POSITION_Y=100;
static const int TIMING_RING1_GRAPH_HEIGHT=20;
static const int TIMING_RING2_GRAPH_INITIAL_POSITION_X=10;
static const int TIMING_RING2_GRAPH_POSITION_Y=130;
static const int TIMING_RING2_GRAPH_HEIGHT=20;

@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize signal=_signal;
@synthesize timingRing1GraphPositionX=_timingRing1GraphPositionX;
@synthesize timingRing2GraphPositionX=_timingRing2GraphPositionX;
@synthesize labelList=_labelList;
@synthesize currentTime=_currentTime;
@synthesize offsetPhaseTime=_offsetPhaseTime;
@synthesize beginTime=_beginTime;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil agency:(Agency *)agency subSystem:(SubSystem *) subSystem timingPattern:(TimingPattern *) timingPattern signal:(Signal *) signal
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.agency=agency;
        self.subSystem=subSystem;
        self.timingPattern=timingPattern;
        self.signal=signal;
        
        self.greenTime=0;
        self.yellowTime=0;
        self.redTime=0;
        
        self.currentRing1PhaseIndex=-1;
        self.currentRing2PhaseIndex=-1;
        
        self.beginTime=nil;
    }
    return self;
}

-(void) dealloc
{
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    [_signal release];
    [_signalNameLabel release];
    [_currentTime release];
    [_ring1Button release];
    [_ring2Button release];
    [_stopButton release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.signalNameLabel.text=self.signal.signalName;
    
    if (!_labelList) {
        _labelList=[[NSMutableArray alloc] init];
    }
    
//    self.ring1Button.frame=CGRectMake(15, 300, 280, 40);
    self.ring1Button.layer.cornerRadius = 20;
    [self.ring1Button.layer setMasksToBounds:YES];
    [self.ring1Button.layer setBorderWidth:1.0f];
    [self.ring1Button.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [self.ring1Button setBackgroundColor:[UIColor whiteColor]];
    [self.ring1Button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.ring1Button setSelected:NO];
    
    self.ring2Button.layer.cornerRadius = 20;
    [self.ring2Button.layer setMasksToBounds:YES];
    [self.ring2Button.layer setBorderWidth:1.0f];
    [self.ring2Button.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [self.ring2Button setBackgroundColor:[UIColor whiteColor]];
    [self.ring2Button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.ring2Button setSelected:NO];
    
    self.stopButton.layer.cornerRadius = 20;
    [self.stopButton.layer setMasksToBounds:YES];
    [self.stopButton.layer setBorderWidth:1.0f];
    [self.stopButton.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [self.stopButton setBackgroundColor:[UIColor redColor]];
    [self.stopButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.stopButton setSelected:NO];
    
    [self.stopButton setHidden:YES];
    
//    if (self.currentRing1PhaseIndex<self.signal.ring1.phaseList.count)
//    {
//        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
//        [self.ring1Button setTitle:[NSString stringWithFormat:@"%@ - %@",phase.phaseID,phase.phaseMovement] forState:UIControlStateNormal];
//        
//    }
//    if (self.currentRing2PhaseIndex<self.signal.ring2.phaseList.count)
//    {
//        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
//        [self.ring2Button setTitle:[NSString stringWithFormat:@"%@ - %@",phase.phaseID,phase.phaseMovement] forState:UIControlStateNormal];
//    }
    
    NSArray *ring1PhaseList=self.signal.ring1.phaseList;
    NSArray *ring2PhaseList=self.signal.ring2.phaseList;
    self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
    self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
    int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
    int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
    
    int ring1BarrierTime=0;
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring1BarrierTime=ring1BarrierTime+self.timingRing1GraphPositionX;
    int ring2BarrierTime=0;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring2BarrierTime=ring2BarrierTime+self.timingRing2GraphPositionX;
    double barrierTime=0;
    if (ring1BarrierTime>=ring2BarrierTime) {
        barrierTime=ring1BarrierTime;
    }else{
        barrierTime=ring2BarrierTime;
    }
    int barrierPositionX=barrierTime;
    
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
            self.timingRing1GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signal.cycleLength floatValue];
        int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signal.cycleLength floatValue];
        int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signal.cycleLength floatValue];
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
        greenLabel.tag=100+i;
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];
//        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
        
        UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    
    
    timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
    timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
            self.timingRing2GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signal.cycleLength floatValue];
        int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signal.cycleLength floatValue];
        int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signal.cycleLength floatValue];
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
        greenLabel.tag=200+i;
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];
//        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        
        //        [self.labelList addObject:greenLabel];
        //        UILabel * tempLabel=[self.labelList objectAtIndex:self.labelList.count-1];
        //        [[self.labelList objectAtIndex:self.labelList.count-1] removeFromSuperview];
        
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
        
        UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    
    
    self.offsetPhaseTime=0;
    
    int i=0;
    for (i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        if ([self.signal.offsetPhase isEqualToString:phase.phaseID]) {
            if ([self.signal.offsetBorE isEqualToString:@"Green End"]) {
                self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                
            }
            break;
        }
        self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
    }
    if (i>=self.signal.ring1.phaseList.count) {
        self.offsetPhaseTime=0;
        for (i=0; i<self.signal.ring2.phaseList.count; i++) {
            SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
            if ([self.signal.offsetPhase isEqualToString:phase.phaseID]) {
                if ([self.signal.offsetBorE isEqualToString:@"Green End"]) {
                    self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                    
                }
                break;
            }
            self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
        }
        if (i>=self.signal.ring2.phaseList.count) {
            self.offsetPhaseTime=0;
        }
    }
    
    
//    [self.phasePicker setHidden:YES];
//    self.phaseOffSetText.enabled=NO;
    
//    if (self.signal.offsetPhase==nil||[self.signal.offsetPhase isEqualToString:@""]) {
//        self.phaseOffSetText.text=@"";
//    }else {
//        self.phaseOffSetText.text=[NSString stringWithFormat:@"Phase %@  %@",self.signal.offsetPhase,self.signal.offsetBorE];
//    }
    
    
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
//    CustomizedBarButtonItem *signalCountingButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"CountingSignal.png"] target:self action:@selector(goToSignalCounting:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,nil ];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    float ring1Cycle=0;
    for (int i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        ring1Cycle=ring1Cycle+[phase.greenTime floatValue]+[phase.yellowTime floatValue]+[phase.allRedTime floatValue];
    }
    float ring2Cycle=0;
    for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
        ring2Cycle=ring2Cycle+[phase.greenTime floatValue]+[phase.yellowTime floatValue]+[phase.allRedTime floatValue];
    }
    self.signal.cycleLength=[NSString stringWithFormat:@"%.1f",MAX(ring1Cycle, ring2Cycle)];
    if (!self.beginTime) {
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }else
    {
        int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength intValue] time:self.beginTime offSet:(0-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        self.signal.offset=[NSString stringWithFormat:@"%d",controllerTimer];
        [XMLParser updateSignal:self.signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setSignalNameLabel:nil];
    [self setRing1Button:nil];
    [self setRing2Button:nil];
    [self setStopButton:nil];
    [super viewDidUnload];
}

- (IBAction)clickRing1Button:(id)sender {
    [self.ring2Button setHidden:YES];
    [self.stopButton setHidden:NO];
    if (self.currentRing1PhaseIndex==-1) {
        self.currentRing1PhaseIndex=0;
        self.beginTime=[NSDate date];
    }
    if (self.currentRing1PhaseIndex>=self.signal.ring1.phaseList.count) {
        self.currentRing1PhaseIndex=0;
        return;
    }
    if (self.greenTime==0) {
        if (self.currentTime) {
            NSDate * tempCurrentTime=[NSDate date];
            self.greenTime=[tempCurrentTime timeIntervalSinceDate:self.currentTime];
            self.currentTime=tempCurrentTime;
            SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
            phase.greenTime=[NSString stringWithFormat:@"%.1f",self.greenTime];
        }else
        {
            self.currentTime=[NSDate date];
            if (self.currentRing1PhaseIndex<self.signal.ring1.phaseList.count)
            {
                SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
                [self.ring1Button setTitle:[NSString stringWithFormat:@"%@ - %@",phase.phaseID,phase.phaseMovement] forState:UIControlStateNormal];
                
                
            }
        }
        
        
    }else if (self.yellowTime==0)
    {
        NSDate * tempCurrentTime=[NSDate date];
        self.yellowTime=[tempCurrentTime timeIntervalSinceDate:self.currentTime];
        self.currentTime=tempCurrentTime;
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
        phase.yellowTime=[NSString stringWithFormat:@"%.1f",self.yellowTime];
//        if (self.currentRing1PhaseIndex<self.signal.ring1.phaseList.count)
//        {
//            SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
//            [self.ring1Button setTitle:[NSString stringWithFormat:@"%@ - %@",phase.phaseID,phase.phaseMovement] forState:UIControlStateNormal];
//            
//            
//        }
        
    }else if (self.redTime==0)
    {
        NSDate * tempCurrentTime=[NSDate date];
        self.redTime=[tempCurrentTime timeIntervalSinceDate:self.currentTime];
        self.currentTime=tempCurrentTime;
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
        phase.allRedTime=[NSString stringWithFormat:@"%.1f",self.redTime];
        self.currentRing1PhaseIndex=self.currentRing1PhaseIndex+1;
        if(self.currentRing1PhaseIndex>=self.signal.ring1.phaseList.count)
        {
            self.currentRing1PhaseIndex=0;
        }
        self.greenTime=0;
        self.yellowTime=0;
        self.redTime=0;
        if (self.currentRing1PhaseIndex<self.signal.ring1.phaseList.count)
        {
            SignalPhase *tempPhase=[self.signal.ring1.phaseList objectAtIndex:self.currentRing1PhaseIndex];
            NSLog(@"%@ - %@",tempPhase.phaseID,phase.phaseMovement);
            [self.ring1Button setTitle:[NSString stringWithFormat:@"%@ - %@",tempPhase.phaseID,tempPhase.phaseMovement] forState:UIControlStateNormal];
//            self.ring1Button.titleLabel.text=[NSString stringWithFormat:@"%@ - %@",tempPhase.phaseID,phase.phaseMovement];
            
            
        }
        
        
        
    }
    if (self.greenTime==0) {
        [self.ring1Button setBackgroundColor:[UIColor greenColor]];
    }else if (self.yellowTime==0) {
        [self.ring1Button setBackgroundColor:[UIColor yellowColor]];
    }else if (self.redTime==0) {
        [self.ring1Button setBackgroundColor:[UIColor redColor]];
    }

    float ring1Cycle=0;
    for (int i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        ring1Cycle=ring1Cycle+[phase.greenTime floatValue]+[phase.yellowTime floatValue]+[phase.allRedTime floatValue];
    }
    float ring2Cycle=0;
    for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
        ring2Cycle=ring2Cycle+[phase.greenTime floatValue]+[phase.yellowTime floatValue]+[phase.allRedTime floatValue];
    }
    self.signal.cycleLength=[NSString stringWithFormat:@"%.1f",MAX(ring1Cycle, ring2Cycle)];
    [self updateSignalLabel];



}

- (IBAction)clickRing2Button:(id)sender {
    [self.ring1Button setHidden:YES];
    [self.stopButton setHidden:NO];
    if (self.currentRing2PhaseIndex==-1) {
        self.currentRing2PhaseIndex=0;
        self.beginTime=[NSDate date];
    }
    if (self.currentRing2PhaseIndex>=self.signal.ring2.phaseList.count) {
        self.currentRing2PhaseIndex=0;
        return;
    }
    if (self.greenTime==0) {
        if (self.currentTime) {
            NSDate * tempCurrentTime=[NSDate date];
            self.greenTime=[tempCurrentTime timeIntervalSinceDate:self.currentTime];
            self.currentTime=tempCurrentTime;
            SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
            phase.greenTime=[NSString stringWithFormat:@"%.1f",self.greenTime];
        }else
        {
            self.currentTime=[NSDate date];
            if (self.currentRing2PhaseIndex<self.signal.ring2.phaseList.count)
            {
                SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
                [self.ring2Button setTitle:[NSString stringWithFormat:@"%@ - %@",phase.phaseID,phase.phaseMovement] forState:UIControlStateNormal];
                
                
            }
        }
        
        
    }else if (self.yellowTime==0)
    {
        NSDate * tempCurrentTime=[NSDate date];
        self.yellowTime=[tempCurrentTime timeIntervalSinceDate:self.currentTime];
        self.currentTime=tempCurrentTime;
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
        phase.yellowTime=[NSString stringWithFormat:@"%.1f",self.yellowTime];
        //        if (self.currentRing2PhaseIndex<self.signal.ring2.phaseList.count)
        //        {
        //            SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
        //            [self.ring2Button setTitle:[NSString stringWithFormat:@"%@ - %@",phase.phaseID,phase.phaseMovement] forState:UIControlStateNormal];
        //
        //
        //        }
        
    }else if (self.redTime==0)
    {
        NSDate * tempCurrentTime=[NSDate date];
        self.redTime=[tempCurrentTime timeIntervalSinceDate:self.currentTime];
        self.currentTime=tempCurrentTime;
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
        phase.allRedTime=[NSString stringWithFormat:@"%.1f",self.redTime];
        self.currentRing2PhaseIndex=self.currentRing2PhaseIndex+1;
        if(self.currentRing2PhaseIndex>=self.signal.ring2.phaseList.count)
        {
            self.currentRing2PhaseIndex=0;
        }
        self.greenTime=0;
        self.yellowTime=0;
        self.redTime=0;
        if (self.currentRing2PhaseIndex<self.signal.ring2.phaseList.count)
        {
            SignalPhase *tempPhase=[self.signal.ring2.phaseList objectAtIndex:self.currentRing2PhaseIndex];
            NSLog(@"%@ - %@",tempPhase.phaseID,phase.phaseMovement);
            [self.ring2Button setTitle:[NSString stringWithFormat:@"%@ - %@",tempPhase.phaseID,tempPhase.phaseMovement] forState:UIControlStateNormal];
//            self.ring2Button.titleLabel.text=[NSString stringWithFormat:@"%@ - %@",tempPhase.phaseID,phase.phaseMovement];
            
            
        }
        
        
        
    }
    if (self.greenTime==0) {
        [self.ring2Button setBackgroundColor:[UIColor greenColor]];
    }else if (self.yellowTime==0) {
        [self.ring2Button setBackgroundColor:[UIColor yellowColor]];
    }else if (self.redTime==0) {
        [self.ring2Button setBackgroundColor:[UIColor redColor]];
    }
    
    float ring1Cycle=0;
    for (int i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        ring1Cycle=ring1Cycle+[phase.greenTime floatValue]+[phase.yellowTime floatValue]+[phase.allRedTime floatValue];
    }
    float ring2Cycle=0;
    for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
        ring2Cycle=ring2Cycle+[phase.greenTime floatValue]+[phase.yellowTime floatValue]+[phase.allRedTime floatValue];
    }
    self.signal.cycleLength=[NSString stringWithFormat:@"%.1f",MAX(ring1Cycle, ring2Cycle)];
    [self updateSignalLabel];

}



-(void) updateSignalLabel
{
    NSArray *ring1PhaseList=self.signal.ring1.phaseList;
    NSArray *ring2PhaseList=self.signal.ring2.phaseList;
    self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
    self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
    int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
    int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
    for (UILabel *label in self.labelList) {
        [label removeFromSuperview];
    }
    self.labelList=[[[NSMutableArray alloc] init] autorelease];
    int ring1BarrierTime=0;
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring1BarrierTime=ring1BarrierTime+self.timingRing1GraphPositionX;
    int ring2BarrierTime=0;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring2BarrierTime=ring2BarrierTime+self.timingRing2GraphPositionX;
    double barrierTime=0;
    if (ring1BarrierTime>=ring2BarrierTime) {
        barrierTime=ring1BarrierTime;
    }else{
        barrierTime=ring2BarrierTime;
    }
    int barrierPositionX=barrierTime;
    
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
            self.timingRing1GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signal.cycleLength floatValue];
        int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signal.cycleLength floatValue];
        int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signal.cycleLength floatValue];
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
        greenLabel.tag=100+i;
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];
        //        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
        
        UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    
    
    
    timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
    timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
            self.timingRing2GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=300*[phase.greenTime doubleValue]/[self.signal.cycleLength floatValue];
        int yellowPhaseLength=300*[phase.yellowTime doubleValue]/[self.signal.cycleLength floatValue];
        int allRedPhaseLength=300*[phase.allRedTime doubleValue]/[self.signal.cycleLength floatValue];
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
        greenLabel.tag=200+i;
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];
        //        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        
        //        [self.labelList addObject:greenLabel];
        //        UILabel * tempLabel=[self.labelList objectAtIndex:self.labelList.count-1];
        //        [[self.labelList objectAtIndex:self.labelList.count-1] removeFromSuperview];
        
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
        
        UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
}
- (IBAction)clickStopButton:(id)sender {
    [self.ring1Button setTitle:@"RING 1 COUNT" forState:UIControlStateNormal];
    [self.ring1Button setBackgroundColor:[UIColor whiteColor]];
    [self.ring2Button setTitle:@"RING 2 COUNT" forState:UIControlStateNormal];
    [self.ring2Button setBackgroundColor:[UIColor whiteColor]];
    [self.ring1Button setHidden:NO];
    [self.ring2Button setHidden:NO];
    [self.stopButton setHidden:YES];
    self.currentTime=nil;
    self.greenTime=0;
    self.yellowTime=0;
    self.redTime=0;
    
    self.currentRing1PhaseIndex=0;
    self.currentRing2PhaseIndex=0;
}
@end
